﻿
/*******************************************************************************************
// ©2009 Microsoft Corporation.  This code is provided under the Microsoft Public License.
*******************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net;

namespace ClientBilling
{
    public class Certificates
    {
        public static X509Certificate2 GetLocalCertificate()
        {
            //Get a handle to the local machine's certificate store
            X509Store store = new X509Store(StoreLocation.LocalMachine);
            //Open the store
            store.Open(OpenFlags.ReadOnly);
            //Get a handle to a collection of the certificates installed on the machine
            X509Certificate2Collection certificates = store.Certificates;
            //Loop through the certificates looking for one 
            //where the SubjectName matches hte FQDN of the
            //Local Machine
            foreach (X509Certificate2 certificate in certificates)
            {
                if (certificate.SubjectName.Name.Contains
                    (Dns.GetHostEntry("localhost").HostName)
                    && certificate.HasPrivateKey)
                {
                    //Return the certificate that matches
                    return certificate;
                }
            }
            //If not certs match, return null
            return null;
        }
    }
}
